<template>
  <div class="history-container">
    <div class="history-wrapper">
      <h2>结算记录</h2>
      
      <!-- 汇总数据卡片 -->
      <el-row :gutter="20" class="summary-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <template #header>总订单数</template>
            <div class="amount">{{ totalStats.orderCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <template #header>房间收入</template>
            <div class="amount">¥{{ formatNumber(totalStats.roomAmount) }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <template #header>商品收入</template>
            <div class="amount">¥{{ formatNumber(totalStats.snackAmount) }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="summary-card">
            <template #header>总收入</template>
            <div class="amount total">¥{{ formatNumber(totalStats.totalAmount) }}</div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <div class="quick-filters">
          <span>时间范围：</span>
          <el-radio-group v-model="timeFilter" @change="handleFilterChange">
            <el-radio-button :value="'all'">全部</el-radio-button>
            <el-radio-button :value="'today'">今天</el-radio-button>
            <el-radio-button :value="'yesterday'">昨天</el-radio-button>
            <el-radio-button :value="'week'">本周</el-radio-button>
            <el-radio-button :value="'lastWeek'">上周</el-radio-button>
            <el-radio-button :value="'month'">本月</el-radio-button>
            <el-radio-button :value="'lastMonth'">上月</el-radio-button>
          </el-radio-group>
        </div>
        <el-input
          v-model="searchQuery"
          placeholder="搜索包房"
          prefix-icon="Search"
          clearable
          style="width: 200px"
        />
      </div>
      
      <div class="history-content">
        <el-table 
          :data="paginatedHistory" 
          v-loading="loading"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column prop="room_name" label="房间" width="80" />
          <el-table-column label="开始时间" width="160">
            <template #default="scope">
              {{ formatTime(scope.row.start_time) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间" width="160">
            <template #default="scope">
              {{ formatTime(scope.row.end_time) }}
            </template>
          </el-table-column>
          <el-table-column label="使用时长" width="160">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column 
            label="备注" 
            prop="remark" 
            min-width="120"
          />
          <el-table-column 
            label="房间费用" 
            prop="base_amount" 
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.base_amount }}
            </template>
          </el-table-column>
          <el-table-column 
            label="商品费用" 
            prop="snack_amount" 
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.snack_amount }}
            </template>
          </el-table-column>
          <el-table-column 
            label="调整金额" 
            prop="adjustment" 
            width="100"
            align="right"
          >
            <template #default="scope">
              <span :style="{ color: scope.row.adjustment < 0 ? '#f56c6c' : '#67c23a' }">
                ¥{{ scope.row.adjustment }}
              </span>
            </template>
          </el-table-column>
          <el-table-column 
            label="总计金额" 
            prop="total_amount" 
            width="100"
            align="right"
            :class-name="'total-column'"
          >
            <template #default="scope">
              ¥{{ scope.row.total_amount }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                @click="showDetail(scope.row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="15"
            layout="total, prev, pager, next, jumper"
            :total="filteredHistory.length"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>

  <!-- 详情对话框 -->
  <el-dialog
    title="结算详情"
    v-model="detailVisible"
    width="500px"
    class="detail-dialog"
  >
    <el-card v-if="selectedRecord" class="detail-card" shadow="never">
      <template #header>
        <div class="detail-header">
          <h3>{{ selectedRecord.room_name }} - 消费明细</h3>
          <el-tag type="success">已完成</el-tag>
        </div>
      </template>
      
      <div class="detail-content">
        <!-- 时间信息 -->
        <div class="time-info">
          <p>开始时间：{{ formatTime(selectedRecord.start_time) }}</p>
          <p>结束时间：{{ formatTime(selectedRecord.end_time) }}</p>
          <p>使用时长：{{ formatDuration(selectedRecord.duration) }}</p>
        </div>
        
        <!-- 零食明细 -->
        <template v-if="selectedRecord.items.length">
          <div class="divider"></div>
          <div class="snack-details">
            <h4>商品明细</h4>
            <div class="snack-items">
              <div 
                v-for="item in selectedRecord.items" 
                :key="item.id" 
                class="snack-item"
              >
                <div class="snack-info">
                  <span class="name">{{ item.snack_name }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
                <span class="subtotal">¥{{ item.subtotal }}</span>
              </div>
            </div>
          </div>
        </template>
        
        <!-- 费用明细 -->
        <div class="divider"></div>
        <div class="fee-details">
          <div class="fee-item">
            <span class="label">房间费用</span>
            <span class="amount">¥{{ selectedRecord.base_amount }}</span>
          </div>
          <div class="fee-item">
            <span class="label">商品费用</span>
            <span class="amount">¥{{ selectedRecord.snack_amount }}</span>
          </div>
          <div class="fee-item" v-if="selectedRecord.adjustment !== 0">
            <span class="label adjustment">
              <el-icon><Discount /></el-icon>
              调整金额
            </span>
            <span :class="['amount', { 'adjustment-negative': selectedRecord.adjustment < 0 }]">
              ¥{{ selectedRecord.adjustment }}
            </span>
          </div>
          <div class="fee-item remark" v-if="selectedRecord.remark">
            <span class="label">备注</span>
            <span class="remark-text">{{ selectedRecord.remark }}</span>
          </div>
          <div class="divider"></div>
          <div class="fee-item total">
            <span class="label">总计金额</span>
            <span class="amount">¥{{ selectedRecord.total_amount }}</span>
          </div>
        </div>
      </div>
    </el-card>
  </el-dialog>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { orderAPI } from '../api/services'
import { ElMessage } from 'element-plus'
import { Discount } from '@element-plus/icons-vue'

export default {
  name: 'History',
  components: {
    Discount
  },
  setup() {
    const orders = ref([])
    const selectedRecord = ref(null)
    const detailVisible = ref(false)
    const searchQuery = ref('')
    const timeFilter = ref('all')
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(15) // 固定每页显示15条

    // 判断日期是否在指定范围内
    const isDateInRange = (date, range) => {
      const recordDate = new Date(date)
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      
      // 本周开始时间
      const weekStart = new Date(today)
      weekStart.setDate(weekStart.getDate() - weekStart.getDay())
      
      // 上周的开始和结束时间
      const lastWeekStart = new Date(weekStart)
      lastWeekStart.setDate(lastWeekStart.getDate() - 7)
      const lastWeekEnd = new Date(weekStart)
      
      // 本月开始时间
      const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
      
      // 上月的开始和结束时间
      const lastMonthStart = new Date(today.getFullYear(), today.getMonth() - 1, 1)
      const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0, 23, 59, 59)
      
      switch (range) {
        case 'today':
          return recordDate >= today
        case 'yesterday':
          return recordDate >= yesterday && recordDate < today
        case 'week':
          return recordDate >= weekStart
        case 'lastWeek':
          return recordDate >= lastWeekStart && recordDate < lastWeekEnd
        case 'month':
          return recordDate >= monthStart
        case 'lastMonth':
          return recordDate >= lastMonthStart && recordDate <= lastMonthEnd
        default:
          return true
      }
    }
    
    // 处理时间筛选变化
    const handleFilterChange = () => {
      // 切换筛选时重置到第一页
      currentPage.value = 1
      // ... 其他筛选逻辑
    }

    // 过滤后的历史记录
    const filteredHistory = computed(() => {
      return orders.value.filter(order => {
        const matchesSearch = order.room_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        const matchesTimeFilter = isDateInRange(order.start_time, timeFilter.value)
        return matchesSearch && matchesTimeFilter

      })
    })
    
    // 计算总计数据
    const totalStats = computed(() => {
      if (!Array.isArray(filteredHistory.value)) return {
        orderCount: 0,
        roomAmount: 0,
        snackAmount: 0,
        totalAmount: 0
      }
      
      return filteredHistory.value.reduce((acc, order) => {
        acc.orderCount++
        acc.roomAmount += order.base_amount
        acc.snackAmount += order.snack_amount
        acc.totalAmount += order.total_amount
        return acc
      }, {
        orderCount: 0,
        roomAmount: 0,
        snackAmount: 0,
        totalAmount: 0
      })
    })

    // 分页后的数据
    const paginatedHistory = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      // 对数据进行排序，最新的订单显示在前面
      const sortedHistory = [...filteredHistory.value].sort((a, b) => {
        return new Date(b.end_time) - new Date(a.end_time)
      })
      return sortedHistory.slice(start, end)
    })

    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      // 滚动到表格顶部
      document.querySelector('.history-content')?.scrollIntoView({ behavior: 'smooth' })
    }

    const formatNumber = (num) => {
      return num.toLocaleString('zh-CN', { 
        minimumFractionDigits: 2, 
        maximumFractionDigits: 2 
      })
    }

    const fetchOrders = async () => {
      loading.value = true
      try {
        const response = await orderAPI.getOrderHistory()
        console.log('Orders response:', response)
        orders.value = response || []  // 直接使用返回的数组
        // 重置分页到第一页
        currentPage.value = 1
      } catch (error) {
        console.error('Failed to fetch orders:', error)
        ElMessage.error('获取历史记录失败')
        orders.value = []
      } finally {
        loading.value = false
      }
    }

    const showDetail = (record) => {
      selectedRecord.value = record
      detailVisible.value = true
    }

    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    }
    
    const formatDuration = (hours) => {
      const totalMinutes = Math.floor(hours * 60)
      const h = Math.floor(totalMinutes / 60)
      const m = totalMinutes % 60
      return h > 0 ? `${h}小时${m}分钟` : `${m}分钟`
    }

    onMounted(async () => {
      await fetchOrders()  // 等待数据加载完成
    })

    return {
      orders,
      detailVisible,
      selectedRecord,
      showDetail,
      formatTime,
      formatDuration,
      searchQuery,
      filteredHistory,
      totalStats,
      paginatedHistory,
      currentPage,
      pageSize,
      handleCurrentChange,
      formatNumber,
      timeFilter,
      handleFilterChange,
      loading
    }
  }
}
</script>

<style scoped>
.history-container {
  position: absolute;
  top: 80px;  /* 顶部导航栏高度 */
  bottom: 0;
  left: 200px;  /* 侧边栏宽度 */
  right: 0;
  overflow: hidden;
  background-color: #f0f2f5;
}

.history-wrapper {
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  box-sizing: border-box;
}

h2 {
  margin: 0 0 20px 0;
  color: #303133;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.quick-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.el-radio-button__inner) {
  padding: 8px 15px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.time-range {
  color: #303133;
}

.duration {
  color: #909399;
  font-size: 13px;
  white-space: nowrap;
}

.total {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.total-column) {
  font-weight: bold;
  color: #f56c6c;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

/* 详情对话框样式 */
.detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.detail-card {
  border: none;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-header h3 {
  margin: 0;
  font-size: 16px;
}

.detail-content {
  padding: 20px;
}

.time-info {
  color: #606266;
}

.time-info p {
  margin: 5px 0;
}

.divider {
  height: 1px;
  background-color: #dcdfe6;
  margin: 15px 0;
}

.snack-details h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.snack-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.snack-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.snack-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name {
  color: #303133;
}

.quantity {
  color: #909399;
  font-size: 13px;
}

.subtotal {
  color: #f56c6c;
  font-weight: 500;
}

.fee-details {
  padding: 0 10px;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  font-size: 15px;
}

.fee-item .label {
  color: #606266;
}

.fee-item .amount {
  color: #303133;
  font-weight: 500;
}

.fee-item.total {
  font-size: 18px;
}

.fee-item.total .label {
  color: #303133;
  font-weight: bold;
}

.fee-item.total .amount {
  color: #f56c6c;
  font-weight: bold;
}

.adjustment-negative {
  color: #67c23a !important;  /* 使用绿色表示优惠金额 */
}

.fee-item.remark {
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin: 10px 0;
  border-left: 3px solid #e6a23c;  /* 添加左边框突出显示 */
}

.remark-text {
  color: #606266;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
}

/* 调整金额的标签样式 */
.fee-item .label.adjustment {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 调整详情卡片的内边距 */
.detail-card :deep(.el-card__body) {
  padding: 0;
}

.detail-content {
  padding: 20px;
}

.summary-cards {
  margin-bottom: 20px;
}

.summary-card {
  text-align: center;
  transition: all 0.3s ease;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-card :deep(.el-card__header) {
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
  background-color: #f5f7fa;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
  color: #409EFF;
}

.amount.total {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

/* 优化表格样式 */
.history-content {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

:deep(.el-table) {
  margin-bottom: 0;
  border-bottom: 1px solid #ebeef5;
}

/* 优化滚动条样式 */
.history-wrapper::-webkit-scrollbar {
  width: 6px;
}

.history-wrapper::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.history-wrapper::-webkit-scrollbar-track {
  background-color: #f0f2f5;
}
</style> 